package com.itbaizhan.shopping_user_service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itbaizhan.shopping_common.pojo.ShoppingUser;
import com.itbaizhan.shopping_common.result.BusException;
import com.itbaizhan.shopping_common.result.CodeEnum;
import com.itbaizhan.shopping_common.service.UserService;
import com.itbaizhan.shopping_common.util.Md5Util;
import com.itbaizhan.shopping_user_service.mapper.ShoppingUserMapper;
import com.itbaizhan.shopping_user_service.util.JwtUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@DubboService
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private ShoppingUserMapper shoppingUserMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void saveRegisterCheckCode(String phone, String checkCode) {
        redisTemplate.opsForValue().set("registerCode:" + phone, checkCode, 300, TimeUnit.SECONDS);
    }

    @Override
    public void checkRegisterCheckCode(String phone, String checkCode) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String redisCode = (String) valueOperations.get("registerCode:" + phone);
        if (redisCode == null || !redisCode.equals(checkCode)) {
            throw new BusException(CodeEnum.REGISTER_CODE_ERROR);
        }
    }

    @Override
    public void register(ShoppingUser shoppingUser) {
        // 1、验证用户是否存在
        // 1.1验证手机号是否存在
        String phone = shoppingUser.getPhone();
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("phone", phone);
        ShoppingUser user = shoppingUserMapper.selectOne(queryWrapper1);
        if (user != null) {
            throw new BusException(CodeEnum.REGISTER_REPEAT_PHONE_ERROR);
        }
        // 1.2 验证用户名是否存在
        String username = shoppingUser.getUsername();
        QueryWrapper queryWrapper2 = new QueryWrapper();
        queryWrapper2.eq("username", username);
        ShoppingUser user2 = shoppingUserMapper.selectOne(queryWrapper2);
        if (user2 != null) {
            throw new BusException(CodeEnum.REGISTER_REPEAT_USERNAME_ERROR);
        }
        // 2、设置用户状态
        shoppingUser.setStatus("Y");
        // 3、密码加密
        String password = shoppingUser.getPassword();
        shoppingUser.setPassword(Md5Util.encode(password));
        // 4、保存用户到数据库
        shoppingUserMapper.insert(shoppingUser);
    }

    @Override
    public String loginPassword(String username, String password) {
        // 根据用户名查询用户
        QueryWrapper<ShoppingUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        ShoppingUser user = shoppingUserMapper.selectOne(wrapper);
        if (user == null) {
            throw new BusException(CodeEnum.LOGIN_NAME_PASSWORD_ERROR);
        }
        // 匹配密码
        if (!Md5Util.verify(password, user.getPassword())) {
            throw new BusException(CodeEnum.LOGIN_NAME_PASSWORD_ERROR);
        }
        return JwtUtils.sign(user.getId(), username);
    }

    @Override
    public void saveLoginCheckCode(String phone, String checkCode) {
        redisTemplate.opsForValue().set("loginCode:" + phone, checkCode, 300, TimeUnit.SECONDS);
    }

    @Override
    public String loginCheckCode(String phone, String checkCode) {
        // 根据手机号查询用户
        QueryWrapper<ShoppingUser> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        ShoppingUser user = shoppingUserMapper.selectOne(wrapper);
        if (user == null) {
            throw new BusException(CodeEnum.LOGIN_PHONE_CODE_ERROR);
        }
        String redisCode = (String) redisTemplate.opsForValue().get("loginCode:" + phone);
        if (redisCode == null || !redisCode.equals(checkCode)) {
            throw new BusException(CodeEnum.LOGIN_PHONE_CODE_ERROR);
        }
        return JwtUtils.sign(user.getId(), user.getUsername());
    }

    @Override
    public String getUsername(String token) {
        Map<String, Object> map = JwtUtils.verify(token);
        String username = (String) map.get("username");
        return username;
    }

    @Override
    public ShoppingUser getLoginUser(String token) {
        Map<String, Object> map = JwtUtils.verify(token);
        Long userId = (Long) map.get("userId");
        return shoppingUserMapper.selectById(userId);
    }

    /**
     * 查询该手机号是否注册，用户状态是否良好
     *
     * @param phone 手机号
     * @return
     */
    public void checkPhone(String phone) {
        QueryWrapper<ShoppingUser> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        ShoppingUser user = shoppingUserMapper.selectOne(wrapper);
        if (user == null) { //用户未注册
            throw new BusException(CodeEnum.LOGIN_PHONE_CODE_ERROR);
        }
        if (user.getStatus() == "N") {
            throw new BusException(CodeEnum.LOGIN_PHONE_CODE_ERROR);
        }
    }
}
